package com.zeedev.flyingsaucer.modules.StoreModule.impl;

import android.content.*;
import com.google.inject.Inject;
import com.zeedev.flyingsaucer.data.ContentValuesDatabaseTree;
import com.zeedev.flyingsaucer.modules.StoreModule.interfaces.Store;
import mobi.zeedev.flyingsaucer.common.DataModule.FlyingSaucerConv.Stores;
import mobi.zeedev.flyingsaucer.common.DataModule.Util;
import mobi.zeedev.flyingsaucer.common.DataModule.tree.DatabaseTree;
import roboguice.util.Ln;

import java.io.Serializable;
import java.util.*;


public class StoreDatabaseModel implements Serializable, Store {

    @Override
    public void setDatabaseTree(DatabaseTree tree) {
        this.saveTreeToDatabase(tree);

        contentQueryMap.requery();

//        this.setChanged();
//        this.notifyObservers();
    }

//    public static final String TAG = "StoreDatabaseModel";


    private ContentQueryMap contentQueryMap = null;

    @Inject
    ContentResolver contentResolver;

    @Inject
    public StoreDatabaseModel(ContentQueryMap contentQueryMap) {
        super();
        this.contentQueryMap = contentQueryMap;
    }

    public Boolean isEmpty() {
        return contentQueryMap.getRows().isEmpty();
    }


    private void saveTreeToDatabase(DatabaseTree tree) {
        String tableName = tree.getRootElement().getValue().toString();
        List<ContentValues> list = ContentValuesDatabaseTree.getContentValues(tree);

        Long now = Calendar.getInstance().getTime().getTime();

        for (ContentValues cvCur : list) {

//            ContentValues curRecord = get(cvCur.getAsString(Stores.NAME));
//            if (curRecord != null) {
//
//
//                cvCur.put(Stores.STORES_KEY, curRecord.getAsLong(Stores.STORES_KEY));
//            }

            cvCur.put(Stores.UPDATED_DATE, now);

        }

        ContentValues[] cvar = list.toArray(new ContentValues[]{});

//        int res = contentResolver.bulkInsert(Stores.CONTENT_URI, cvar);

//        contentResolver.acquireContentProviderClient(Stores.CONTENT_URI).
        ContentProviderClient client = contentResolver.acquireContentProviderClient(Stores.CONTENT_URI);
        ArrayList<ContentProviderOperation> opList = new ArrayList<ContentProviderOperation>();
//        ContentProviderOperation.


        for (ContentValues cv : list) {
//            ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Stores.CONTENT_URI);
//            cv.putNull(Stores.STORES_KEY);
            ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(Stores.CONTENT_URI);
//            ContentProviderOperation.newAssertQuery(Stores.CONTENT_URI).build().
            builder.withSelection(Stores.NUMBER + " =?", Util.asAr(cv.getAsString(Stores.NUMBER)));
            ContentProviderOperation bo = builder.withValues(cv).withYieldAllowed(true).build();
            opList.add(bo);
        }

        ContentProviderResult[] cpr = null;
        try {
            cpr = client.applyBatch(opList);
        } catch (Exception e) {
            Ln.e(e);
        }


        int loop = 0;
        opList.clear();
        for (ContentProviderResult result : cpr) {
            if (result.count < 1) {

                ContentProviderOperation.Builder builder2 = ContentProviderOperation.newInsert(Stores.CONTENT_URI).withValues(list.get(loop)).withYieldAllowed(true);
                opList.add(builder2.build());
            }
            loop++;

        }

        ContentProviderResult[] cpr2 = null;
        try {
            cpr2 = client.applyBatch(opList);
        } catch (Exception e) {
            Ln.e(e);
        }


        client.release();


        contentResolver.notifyChange(Stores.CONTENT_URI, null);


    }

/*    private static void saveStoreUrlModelToDatabase(ContentResolver cr, Map<String, String> rawMap) {

        Long now = Calendar.getInstance().getTime().getTime();

        List<ContentValues> cvList = new ArrayList<ContentValues>();

        for (Entry<String, String> entry : rawMap.entrySet()) {
            String url = BeerConstants.BEERKNURD_URL_ROOT + entry.getValue() + "beer";

            ContentValues cv = new ContentValues();
            cv.put(Store.NAME, entry.getKey());
            cv.put(Store.URL, url);
            cv.put(Store.URL_NAME, entry.getValue());
            cv.put(Store.UPDATED_DATE, now);

            cvList.add(cv);
        }
        ContentValues[] cvar1 = new ContentValues[0];
        ContentValues[] cvar = cvList.toArray(cvar1);

        int res = cr.bulkInsert(Store.CONTENT_URI, cvar);

        cr.notifyChange(Store.CONTENT_URI, null);
    }*/

//    @Override
//    public Map<String, String> getNameIdStoreMap() {
//
//        return null;
//    }

    @Override
    public Set<String> keySet() {
        return contentQueryMap.getRows().keySet();
    }


    @Override
    public String get(Object storeName, String columnName) {
        ContentValues o = contentQueryMap.getRows().get(storeName);
        if (o != null) {
            return o.getAsString(columnName);
        } else {
            return null;
        }
    }


    public ContentValues get(Object storeName) {
        ContentValues o = contentQueryMap.getRows().get(storeName);
        return o;
//        if (o != null) {
//            return o;
//        } else {
//            return null;
//        }
    }
/*
    public void markAndNotify() {
        this.setChanged();
        this.notifyObservers();
    }*/


    @Override
    public String get(String columnId, Object keyValue, String columnNameDesired) {
        String ret = null;
        for (Map.Entry<String, ContentValues> entry : contentQueryMap.getRows().entrySet()) {
            String cvSaught = entry.getValue().getAsString(columnId);
            if (cvSaught.equals(keyValue)) {
                if (columnNameDesired.equals(Stores.NAME)) {
                    ret = entry.getKey();
                } else {
                    ret = entry.getValue().getAsString(columnNameDesired);
                }


                break;
            }
        }
        return ret;
    }


}
